<template>
    <div class="app-container">
        <el-button type="primary" @click="handleCreate" class="zdy-btn zdy-btn-rent">创建秘钥
            <img class="lines-img" src="@/assets/img/yunji-jiant.png" alt="">
        </el-button>
        <el-button type="primary" icon="el-icon-plus" @click="createXuanhao" class="zdy-btn zdy-btn-rent">上号链接
        </el-button>
        <el-form :model="formData" ref="formDataForm" :inline="true" class="search-form-new" label-width="68px">

            <el-form-item label="QQ号" prop="accountId">
                <el-select v-model="formData.accountId" filterable clearable  placeholder="请选择QQ号" style="width: 100%">
                    <el-option v-for="item in hangUpQQList" :key="item.id" :label="item.account" :value="item.id" />
                </el-select>
            </el-form-item>
              <el-form-item label="游戏名称" prop="gameId">
                <el-select v-model="formData.gameId" placeholder="请选择游戏" style="width: 100%" clearable >
                    <el-option v-for="dict in allGameList" :key="dict.id" :label="dict.name" :value="dict.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="用户名" prop="useUserName" label-width="55px">
                <el-input v-model="formData.useUserName" placeholder="请输入用户名" clearable size="small" />
            </el-form-item>
            <el-form-item label="秘钥" prop="code" label-width="48px">
                <el-input v-model="formData.code" placeholder="请输入秘钥" clearable size="small" />
            </el-form-item>
            <el-form-item label="状态" prop="codeStatus" label-width="48px">
                <el-select v-model="formData.codeStatus" placeholder="请选择状态" clearable size="small">
                    <el-option label="未失效" value="1" />
                    <el-option label="已失效" value="2" />
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="small" @click="handleSearch">
                    搜索
                </el-button>
                <el-button type="warning" icon="el-icon-refresh" size="small" @click="handleReset">
                    重置
                </el-button>
            </el-form-item>

        </el-form>
        <div class="table_box table_box_new">
            <el-table v-loading="loading" :data="cardSecretList" border style="width: 100%">
                <el-table-column prop="id" label="id" width="80" />
                <el-table-column v-if="checkPermi(['searchTenantID'])" prop="tenantId" label="店铺ID" width="80" />
                <el-table-column v-if="checkPermi(['searchTenantID'])" prop="tenantName" label="店铺名称" width="140" />
                <el-table-column prop="account" label="QQ号" width="160" />
                <el-table-column prop="useUserName" label="用户名" width="160" />
                 <el-table-column prop="gameName" label="游戏" width="140" />
                <el-table-column prop="remark" label="备注" width="160" />
                <el-table-column prop="code" label="秘钥" show-overflow-tooltip width="300">
                    <template slot-scope="scope">
                        <span>{{ scope.row.code }}</span>
                        <el-button type="text" icon="el-icon-document-copy" style="margin-left: 10px"
                            @click="copyToClipboard(scope.row)" />
                    </template>
                </el-table-column>
                <el-table-column prop="expireTime" label="状态" width="180">
                    <template slot-scope="scope">
                        <el-tag type="danger" v-if="isTimeExpired(scope.row.expireTime, true)">已失效</el-tag>
                        <el-tag v-else>未失效</el-tag>

                    </template>
                </el-table-column>


                <el-table-column prop="createTime" label="创建时间" width="180">
                    <template slot-scope="scope">
                        {{ scope.row.createTime ? $formatDate(scope.row.createTime) : '' }}
                    </template>
                </el-table-column>

                <el-table-column prop="expireTime" label="到期时间" width="180">
                    <template slot-scope="scope">
                        {{ scope.row.expireTime ? $formatDate(scope.row.expireTime) : '' }}
                    </template>
                </el-table-column>

                <el-table-column label="操作" width="240" fixed="right">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" @click="createXuanhao(scope.row)">
                            复制链接
                        </el-button>

                        <el-button v-if="!isTimeExpired(scope.row.expireTime, true)" size="mini" type="primary"
                            @click="handleInvalidate(scope.row)">
                            立即失效
                        </el-button>
                        <el-button size="mini" type="warning" @click="handleEditdate(scope.row)">
                            修改秘钥
                        </el-button>
                        <!-- <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
                            删除
                        </el-button> -->
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="formData.pageNum"
                :limit.sync="formData.pageSize" @pagination="getList" />
            <!-- 创建卡密弹窗 -->
            <card-secret-modal :visible.sync="dialogVisible" :hang-up-q-q-list="hangUpQQList" @success="getList"
                ref="cardSecretModal" />
        </div>

        <el-dialog title="上号链接" :visible.sync="qrCodeShow" width="620px">
            <div v-if="qrCodeShow" ref="qrcode" style="width:200px; height:200px;margin:0 auto;margin-bottom:15px">
            </div>
            <div class="link-box">
                <div class="" style="text-align: center;">
                    <span class="mylink"> <a :href="phoneLink" target="_blank">{{ phoneLink }}</a></span>
                    <el-button type="primary" size="mini" @click="copy(phoneLink)">复制</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {

    getAllList,

} from '@/api/tenantApis/cloudMachine'
import QRCode from "qrcodejs2";
import cardSecretApi from '@/api/tenantApis/cardSecret'
import Pagination from '@/components/Pagination/index.vue'
import CardSecretModal from './CardSecretModal.vue'

export default {
    computed: {

     allGameList() {
        return this.$store.getters.allGameList;
      },
        shopInfo() {
            return this.$store.getters.shopInfo;
        },
          retailDomain() {
      return this.$store.getters.retailDomain;
    },
    },
    name: 'CardSecretManagement',
    components: { Pagination, CardSecretModal },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 总条数
            total: 0,
            // 已挂机QQ号列表
            hangUpQQList: [],
           
            cardSecretList: [],
          
            formData: {
                pageNum: 1,
                pageSize: 10,
            },
            // 弹窗显示状态
            dialogVisible: false,

            qrCodeShow: false,
            qrcode: null,
            phoneLink: ''
        }
    },
    created() {
        this.getHangUpQQList()
        this.getList()
    },
    methods: {
        /** 查询已挂机QQ号列表 */
        getHangUpQQList() {
            let data = {
                pageNum: 1,
                pageSize: 99999,
                onlineStatus:2
            }
            getAllList(data).then(response => {
                this.hangUpQQList = response.rows || []
            }).catch(error => {
                this.hangUpQQList = []
            })
        },
        handleSearch() {
            this.formData.pageNum = 1
            this.getList()
        },
        // 重置查询参数
        resetQueryParams() {
            this.loginTime = []
            this.formData = {
                pageNum: 1,
                pageSize: 10,
                useUserName: '',
                accountId: '',
                code: '',
            }
        },
        handleReset() {
            this.resetQueryParams()
            this.getList()
        },
        /** 查询卡密列表 */
        getList() {
            this.loading = true
            cardSecretApi.getCardSecretList(this.formData).then(response => {
                this.cardSecretList = response.rows || []
                this.total = response.total || 0
                this.loading = false
            }).catch(error => {
                this.cardSecretList = []
                this.total = 0
                this.loading = false
            })
        },

        /** 打开创建卡密弹窗 */
        handleCreate() {
            this.dialogVisible = true
        },

        /** 立即失效 */
        handleInvalidate(row) {
            this.$modal.confirm('确认要立即使该秘钥失效吗？').then(() => {
                return cardSecretApi.expire(row.id)
            }).then(() => {
                this.$modal.msgSuccess('卡密已失效')
                this.getList()
            })
        },
        handleEditdate(row) {
            this.$refs.cardSecretModal.open(row)
            this.dialogVisible = true
        },
        /** 删除 */
        // handleDelete(row) {
        //     this.$modal.confirm('确认要删除该卡密吗？').then(() => {
        //         return cardSecretApi.deleteCardSecret(row.id)
        //     }).then(() => {
        //         this.$modal.msgSuccess('删除成功')
        //         this.getList()
        //     }).catch(error => {
        //         if (error !== 'cancel') {
        //             console.error('删除卡密失败:', error)
        //             this.$modal.msgError('删除卡密失败: ' + (error.message || ''))
        //         }
        //     })
        // },

        /** 复制到剪贴板 */
        copyToClipboard(row) {

            this.$copyText(row.code).then(() => this.$message.success('已复制到剪贴板'));
            // if (this.shopInfo.domain) {
            //     const domain = this.shopInfo.domain.split(',')
            //     if (domain.length > 0) {
            //         const link = `http://${domain[0]}/pages/qrLink/qrLink?code=${row.code}&account=${row.account}`;
            //         this.$copyText(link).then(() => this.$message.success('已复制到剪贴板'));
            //     } else {
            //         this.$message.error('暂无地址');
            //     }
            // }
        },

        createXuanhao(row) {
            this.qrCodeShow = true;
            this.qrCodeShow = true;
            let host = "";
            let str = this.shopInfo.otherDomain
            if (this.shopInfo.otherDomain) {
                if (
                    str.includes('，') || str.includes(',')
                ) {
                    host = "https://" + this.shopInfo.otherDomain.split(/,|，/)[0] + "/pages/qrLink/qrLink";
                } else {
                    host = "https://" + this.shopInfo.otherDomain + "/pages/qrLink/qrLink";
                }
            }else{
                 host = this.retailDomain["h5"].dictValue + "pages/qrLink/qrLink";
            }
            if (row && row.code) {
                this.phoneLink = `${host}?code=${row.code}`;
            } else {
                this.phoneLink = `${host}`
            }
            this.$nextTick(() => {
                if (this.qrcode != null) {
                    this.qrcode.clear(); // 清除代码
                } else {
                }
                this.qrcode = new QRCode(this.$refs.qrcode, {
                    width: 200,
                    height: 200,
                    correctLevel: QRCode.CorrectLevel.L,
                });
                //生成二维码
                this.qrcode.makeCode(this.phoneLink);
            });
        },
        copy(txt) {
            this.$copyText(txt).then((res) => {
                this.$message.success("已复制到剪切板");
            });
    },
    }
}
</script>

<style scoped lang="scss">
.app-container {
    padding: 20px;
}

.mb8 {
    margin-bottom: 8px;
}

.lines-img {
    margin-top: 2px;
    vertical-align: text-top;
    width: 18px;
    margin-left: 2px;
}

.table_box {
    margin-top: 10px;
}

.search-form-new {
    margin-top: 10px;
}
 .mylink {
    margin-right: 10px;
     a {
      color: $primary;
    }
  }
    
</style>